package cn.jtool.dig.server.comm.real;

import cn.jtool.dig.common.model.*;
import cn.jtool.dig.common.netty.CtxUtils;
import cn.jtool.dig.common.netty.SNGenerator;
import cn.jtool.dig.common.netty.SessionManager;
import cn.jtool.dig.server.comm.MessageExchange;
import cn.jtool.dig.server.dao.entity.PortMapping;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ChannelHandler.Sharable
public class RealDataHander extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
        byte[] bytes = new byte[byteBuf.writerIndex() - byteBuf.readerIndex()];
        byteBuf.readBytes(bytes);

        PortMapping portMapping = CtxUtils.getAttribute(ctx, RealAttrKey.OUTWARD_DIG_CONF);
        Long sessionId = CtxUtils.getAttribute(ctx, RealAttrKey.SESSION_ID);

        Session session = SessionManager.getSession(sessionId);
        session.addReceiveByte(bytes.length);
        session.addTrafficBySegment(Session.TrafficDir.REC, bytes.length);

        PacketHeader header = new PacketHeader();
        header.setCommand(Commands.DATA_TRANSPARENT.getCode());
        header.setDigId(portMapping.getLicenseId());
        header.setChannelId(sessionId);
        header.setSn(SNGenerator.gen());
        MessageExchange.upData(Packet.builder().header(header).body(new PacketBody(bytes)).build());
    }

}
